# -*- coding: utf-8 -*-

__author__ = """WebLion <support@weblion.psu.edu>"""
__docformat__ = 'plaintext'

#
# Test-cases for class(es) 
#

from Products.ContactsDirectory.config import *
from Products.ContactsDirectory.tests.testPlone import testPlone

class testContactsDirectory(testPlone):
    """Test-cases for class(es) ."""

    def afterSetUp(self):
        self.loginAsPortalOwner()

    def testFTISetup(self):
        """ Make sure the FTI is pulling info from the GS types profile """
        self.failUnless(self.portal.portal_types['CDContactsDirectory'].Title() != "AT Content Type")

    def testGetGroupsFolder(self):
        cd = self.getPopulatedDirectory()
        groupsFolder = cd.getGroupsFolder()
        self.failUnless(groupsFolder.Title() == 'Groups')
        self.failUnless(groupsFolder.Type() == 'Groups Folder')

    def testDirectoryCreation(self):
        #Make sure the ContactsDirectory was created
        self.portal.invokeFactory(type_name = "CDContactsDirectory", id="test_directory")
        self.failUnless('test_directory' in self.portal.contentIds())

    def testDirectory_at_post_create(self):
        #Make sure the autogenerated content is properly created
        cd = self.getPopulatedDirectory()
        #Check for autogenerated content
        self.failUnless('faculty' in cd.contentIds())
        self.failUnless('staff' in cd.contentIds())
        self.failUnless('grad-students' in cd.contentIds())
        self.failUnless('organizations' in cd.contentIds())
        self.failUnless('groups' in cd.contentIds())

    def testGetClassifications(self):
        cd = self.getPopulatedDirectory()
        classificationsBrains = cd.getClassifications()
        self.failUnless('faculty' in [c.getObject().id for c in classificationsBrains])
        for c in classificationsBrains:
            self.failUnless(c.portal_type == 'CDClassification')

    def testGetProvinces(self):
        cd = self.getPopulatedDirectory()
        classificationsBrains = cd.getProvinces()
        for c in classificationsBrains:
            self.failUnless(c.portal_type == 'CDProvince')


    def testGetPeople(self):
        cd = self.getPopulatedDirectory()
        person = self.getPerson(id='abc123', firstName="Test", lastName="Person")        
        personList = cd.getPeople()
        self.failUnless(person in personList)        
        for c in personList:
            self.failUnless(c.portal_type == 'CDPerson')
        
    def testObjectReorder(self):
        cd = self.getPopulatedDirectory()
        #Try to move a Classification to the top
        cd.moveObjectsByDelta(['staff'], -100)
        self.failUnless(cd.getObjectPosition('staff') == 0, "CDClassification Subobject 'staff' should be at position 0.")
        cd.moveObjectsByDelta(['organizations'], -100)
        self.failUnless(cd.getObjectPosition('organizations') == 0, "CDOrganizationsFolder Subobject 'organizations' should be at position 0.")
        cd.moveObjectsByDelta(['groups'], -100)
        self.failUnless(cd.getObjectPosition('groups') == 0, "CDGroupsFolder Subobject 'groups' should be at position 0.")

    # tests for membrane integration
    def testCDIsGroup(self):
        """Verify that CDs are seen as groups
        """
        cd = self.getPopulatedDirectory()
        self.failUnless(self.portal.portal_groups.getGroupById(cd.id),"unable to find group with id of this cd: %s" % cd.id)
    
    # now test the functionality of the IGroup adapter (membership.contactsdirectory.py)
    def testIGroupAdapter(self):
        """Verify all methods of the IGroup adapter to the ContactsDirectory content type
        """
        from Products.membrane.interfaces import IGroup
        from Products.CMFCore.utils import getToolByName
        
        cd = self.getPopulatedDirectory()
        wf = getToolByName(cd,'portal_workflow')
        
        #adapt to IGroup
        g = IGroup(cd)
        
        #group title is the content object title
        cd.setTitle("My CD")
        self.failUnless(g.Title()=="My CD")
        
        #roles are set on the object, but only available when object is published
        cd.setRoles(('Reviewer',))
        # at first, object is 'visible', but not published, roles should be empty
        self.failIf('Reviewer' in g.getRoles(),"roles are active, but content unpublished\nRoles: %s\nReviewState: %s" % (g.getRoles(), wf.getInfoFor(cd,'review_state')))
        #publish object
        wf.doActionFor(cd,'publish')
        # now check again, role should be there
        self.failUnless('Reviewer' in g.getRoles(),"Roles not active, but content published\nRoles: %s\nReviewState: %s" % (g.getRoles(), wf.getInfoFor(cd,'review_state')))
        
        # group id is set on content object, uniqueness is enforced elsewhere
        self.failUnless(g.getGroupId()==cd.getId(),"getGroupId returning incorrect value:\nExpected: %s\nReceived: %s" % (cd.getId(), g.getGroupId()))
        
        #members are obtained correctly
        self.person1 = self.getPerson(id='abc123', firstName="Test", lastName="Person")
        self.person2 = self.getPerson(id='def456', firstName="Testy", lastName="Persons")
        self.person3 = self.getPerson(id='ghi789', firstName="Tester", lastName="Personage")
        members = list(g.getGroupMembers())
        members.sort()
        self.failUnless(members == ['abc123','def456','ghi789'],"incorrect member list: %s" % members)
        
    def testValidateId(self):
        """Test that the validate_id validator works properly
        """
        from Products.CMFCore.utils import getToolByName
        
        # setup some content to test against
        cd = self.getPopulatedDirectory()
        self.portal.invokeFactory('Document','doc1')
        pg = getToolByName(cd,'portal_groups')
        pg.addGroup('group1');
        
        #allow unused id
        self.failUnless(cd.validate_id('foo')==None,"failed to validate_id 'foo': %s" % cd.validate_id('foo'))
        # allow current object id
        self.failUnless(cd.validate_id('facultstaffdirectory')==None,"Failed to validate current id of cd object: %s" % cd.id)
        # deny id of other object in site
        self.failUnless('doc1' in cd.validate_id('doc1'),"Allowed id 'doc1', even though there is an object with that id in the portal: %s" % cd.validate_id('doc1'))
        # deny id of other group for site
        self.failUnless('group1' in cd.validate_id('group1'),"Allowed id 'doc1', even though there is a group with that id in the portal: %s" % cd.validate_id('group1'))
        
    def testCDImpliesRoles(self):
        """Verify that published CD provides roles to user, where unpublished CD does not
        """
        #set up content
        self.directory = self.getPopulatedDirectory()
        self.person = self.getPerson(id='abc123', firstName="Test", lastName="Person")
        from Products.CMFCore.utils import getToolByName
        wf = getToolByName(self.directory,'portal_workflow')
        
        user = self.portal.portal_membership.getMemberById('abc123')
        # no roles on directory yet, should not find one in the global roles for user
        self.failIf('Reviewer' in user.getRolesInContext(self.portal),"roles from directory available on person, but directory roles unset %s" % user.getRolesInContext(self.portal))
        
        self.directory.setRoles(('Reviewer',))
        user = self.portal.portal_membership.getMemberById('abc123')
        # roles set,but directory is unpublished, should not find roles in global roles for user
        self.failIf('Reviewer' in user.getRolesInContext(self.portal),"roles from directory available on person, but directory unpublished %s" % user.getRolesInContext(self.portal))

        wf.doActionFor(self.directory,'publish')
        user = self.portal.portal_membership.getMemberById('abc123')
        self.failUnless('Reviewer' in user.getRolesInContext(self.portal),"roles from directory unavailable on person, but directory is published %s %s" % (user.getRolesInContext(self.portal),wf.getInfoFor(self.directory,'review_state')))

    # end tests for membrane integration

def test_suite():
    from unittest import TestSuite, makeSuite
    suite = TestSuite()
    suite.addTest(makeSuite(testContactsDirectory))
    return suite
